<template>
  <div>
    <el-upload action="#" ref="upload" list-type="picture-card" multiple :file-list="filelist" :on-preview="preview"
      :on-change="onchange" :on-remove="handleRemove" :auto-upload="false" :accept="accept" :limit="limit"
      :class="{hide: this.filelist.length >= this.limit}">
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-image-viewer v-if="showViewer" :initialIndex="initialIndex" :on-close="closeViewer" :url-list="fileviews"
      :z-index="9999" />
  </div>

</template>

<script>
  import ElImageViewer from 'element-ui/packages/image/src/image-viewer';
  export default {
    name: "uploadfj",
    components: {
      ElImageViewer
    },
    props: {
      value: [String, Object, Array],
      limit: {
        type: Number,
        default: 5,
      },
      accept: {
        type: String,
        default: () => {
          return ".jpg,.png,.pdf,.doc,.docx,.xls,.xlsx";
        }
      }
    },
    data() {
      return {
        showViewer: false,
        initialIndex: 0,
        filelist: [],
        fileviews: [],
        baseUrl: process.env.VUE_APP_BASE_API,
      }
    },
    mounted() {

    },
    watch: {
      value: {
        handler(val) {
          if (val) {

            // 首先将值转为数组
            const list = Array.isArray(val) ? val : this.value.split(',');
            // 然后将数组转为对象数组
            this.filelist = list.map(item => {
              if (typeof item === "string") {
                if (item.indexOf(this.baseUrl) === -1) {
                  item = {
                    name: this.baseUrl + item,
                    url: this.baseUrl + item
                  };
                } else {
                  item = {
                    name: item,
                    url: item
                  };
                }
              }
              return item;
            });
          } else {
            this.filelist = [];
            return [];
          }
        },
        deep: true,
        immediate: true
      }
    },
    activated() {

    },
    methods: {
      getFileExt(fileName) {

        const lastDotIndex = fileName.lastIndexOf('.');
        if (lastDotIndex === -1) {
          return '';
        }
        return fileName.slice(lastDotIndex + 1);
      },

      closeViewer() {
        this.showViewer = false;
      },
      getimg(file) {
        const exts = ["png", "jpg"];
        var img = false;
        if (typeof(file) == 'object') {
          if (file.status == 'success') {
            const keys = Object.keys(file);
            if (keys.includes('resource')) {
              var url = file.resource.filename;
            } else {
              var url = file.url;
            }
            if (exts.indexOf(this.getFileExt(url)) > -1) {
              img = true;
            }
          } else {
            const type = file.raw.type;
            if (type.indexOf('image') >= 0) {
              img = true;
            }
          }
        } else {
          if (exts.indexOf(this.getFileExt(file)) > -1) {
            img = true;
          }
        }
        return img;
      },
      preview(file) {
        if (this.getimg(file)) {
          let that = this;
          this.fileviews = [];
          this.initialIndex = 0
          this.filelist.forEach(function(item, index, arr) {
            if (that.getimg(item) >= 0) {
              that.fileviews.push(item.url);
              if (item == file) that.initialIndex = that.fileviews.length - 1;
            }
          })
          if (that.fileviews.length > 0) this.showViewer = true
        } else if (file.status == 'success') {
          window.open(file.url);
        } else {
          let hsk = file;
          let URL = window.URL || window.webkitURL;
          // 获取分辨率，需要先生成预览url再创建video对象
          let url = URL.createObjectURL(hsk.raw);
          window.open(url);
        }
      },
      onchange(file, fileList) {
        const type = file.raw.type;
        if (type.indexOf('image') == -1) {
          file.url = this.Get_type_file(file.name);
        }
        this.filelist = fileList;
        this.$emit("input", this.filelist);


      },
      handleRemove(file, fileList) {
        this.filelist = fileList;
        this.$emit("input", this.filelist);
      }
    }
  }
</script>

<style scoped lang="scss">
  // .el-upload--picture-card 控制加号部分
  ::v-deep.hide .el-upload--picture-card {
    display: none;
  }

  // 去掉动画效果
  ::v-deep .el-list-enter-active,
  ::v-deep .el-list-leave-active {
    transition: all 0s;
  }

  ::v-deep .el-list-enter,
  .el-list-leave-active {
    opacity: 0;
    transform: translateY(0);
  }
</style>
